/**
 * axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios';
import Qs from 'qs'
import 'nprogress/nprogress.css' // progress bar style
import { getItem, removeItem } from '@/utils/auth' // get token from cookie
// import QS from 'qs';
import { ElMessage } from 'element-plus'
let pending = []; //声明一个数组用于存储每个ajax请求的取消函数和ajax标识
let cancelToken = axios.CancelToken;

let removePending = (ever) => {
  for (let p in pending) {
    if (pending[p] && (pending[p].u === ever.url + '&' + ever.method)) { //当当前请求在数组中存在时执行函数体
      pending[p].f(); //执行取消操作
      pending.splice(p, 1); //把这条记录从数组中移除
    }
  }
}
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_WEWORK_LINK,
  timeout: 30000, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  }

})
// 请求拦截器
service.interceptors.request.use(
  options => {
    options.headers['authentication'] = getItem('token') || "";
    removePending(options); //在一个ajax发送前执行一下取消操作
    options.cancelToken = new cancelToken((c) => {
      pending.push({ u: options.url + '&' + options.method, f: c });
    });

    return options;
  },
  error => {
    return Promise.reject(error);
  });
// 响应拦截器
service.interceptors.response.use(
  response => {
    removePending(response.config);
    if (typeof response == 'string') {
      response = JSON.parse(response);
    }
    if (response.status === 200) { //200说明请求成功

      return Promise.resolve(response.data);
    } else {

      return Promise.reject(response);
    }
  },
  // 服务器状态码不是200的情况
  error => {
    if (error.response && error.response.status == 401) {
      ElMessage.error('登录已过期，请重新登录');
      removeItem('token')
      return Promise.reject(error);
    }
    if (error.response && (error.response.status == 400 || error.response.status == 500)) {
      ElMessage.error(error.response.data.error);
      return Promise.reject(error);
    }
    if (error.response && error.response.data) ElMessage.error(error.response.data.error);

    return Promise.reject(error);
  },

);

export function Get(url, params) {
  return service.get(url, { params });
}

export function Post(url, params) {
  return service.post(url, params, {
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
    }
  });
}
export function PostUpload(url, params) {
  return service.post(url, params, {
    headers: {
      'Content-Type': 'multipart/form-data',
    }
  });
}
export function PostForm(url, params, data) {
  let qs = Qs.stringify(params);
  // url = url + '?' + qs
  return service.post(url, qs);
}
export function Put(url, params) {
  return service.put(url, params, {
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
    }
  })
}
export function PutForm(url, params, data) {
  let qs = Qs.stringify(params);
  return service.put(url, qs);
}
export function Delete(url, params, data) {
  let qs = Qs.stringify(params);
  if (qs) {
    url = url + '?' + qs
  }

  return service.delete(url, data);
}